﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using CommandLib.Base;
using System.Text.RegularExpressions;

namespace My12306
{
    public partial class FrmLogin : Form
    {

        public bool IsRun = false;
        public bool IsClosed = false;
        private object m_lock = new object();
        private FrmMain frmMain;
        public bool IsLogin;
       
        public FrmLogin()
        {
            InitializeComponent();
            this.RefreshCheckCode();

        }
        public FrmLogin(FrmMain frmMain)
        {
            this.InitializeComponent();
            this.frmMain = frmMain;
            this.RefreshCheckCode();
        }

        /// <summary>
        /// 关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.IsClosed = true;
            this.IsRun = false;
        }

        /// <summary>
        /// 验证码单击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void picCheckCode_Click(object sender, EventArgs e)
        {
            this.RefreshCheckCode();
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                this.btnLogin.Enabled = false;
                Thread thread = new Thread(new ThreadStart(this.RunLogin));
                thread.IsBackground = true;
                this.IsRun = true;
                thread.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                Log.WriteLog4Ex("btnLogin_Click", ex);
            }
        }

        private void RunLogin()
        {
            try
            {
                this.frmMain.ChangeState("登录中");
                while (this.IsRun && this.Login())
                {
                    Thread.Sleep(2000);
                }
            }
            catch (Exception ex)
            {
                this.frmMain.WriteInfo("发送错误，错误详细信息：" + ex.Message);
                Log.WriteLog4Ex("RunLogin", ex);
            }
            finally
            {
                lock (this.m_lock)
                {
                    if (!this.IsClosed)
                    {
                        base.BeginInvoke(
                            (MethodInvoker)delegate()
                            {
                                this.btnLogin.Enabled = true;
                                if (!this.frmMain.IsLogin)
                                {
                                    MessageBox.Show("自动登录已停止，如未登录成功，请手动重试！", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                                }
                            }
                        );
                    }
                }
                this.frmMain.ChangeState("待命");
            }
        }
        private bool Login()
        {
            bool result;
            try
            {
                
                string text = this.frmMain.http.PostPage(string.Format("https://dynamic.12306.cn/otsweb/loginAction.do?method=login&loginUser.user_name={0}&nameErrorFocus=&passwordErrorFocus=&randCode={2}&randErrorFocus=focus&user.password={1}", this.txtUserName.Text, this.txtPassWord.Text, this.txtCheckCode.Text), "", Encoding.UTF8, "text/html");
                this.frmMain.WriteHtml(text);
              
                if (this.frmMain.rexLogin.Match(text).Success)
                {
                   
                    this.frmMain.WriteInfo("登录成功!");
                    this.frmMain.WriteInfo("Cookie:dynamic.12306.cn/otsweb/\r\n" + this.frmMain.http.GetCookieStr(new Uri("https://dynamic.12306.cn/otsweb/")));
                    base.BeginInvoke(
                        (MethodInvoker)delegate()
                        {
                            lock (this.m_lock)
                            {
                                MessageBox.Show("登录成功!", "信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                                base.Close();
                                this.frmMain.IsLogin = true;
                                this.frmMain.NavigateMain();
                            }
                        }
                    );
                }
                else
                {
                    Match match = this.frmMain.rexEx2.Match(text);
                    if (!match.Success)
                    {
                        match = this.frmMain.rexEx.Match(text);
                    }
                    if (match.Success)
                    {
                        if (match.Groups[1].Value.Contains("当前访问用户过"))
                        {
                            this.frmMain.WriteInfo(match.Groups[1].Value);
                            result = true;
                            return result;
                        }
                        this.frmMain.WriteInfo(match.Groups[1].Value + "登录已中止！");
                    }
                    else
                    {
                        this.frmMain.WriteInfo("未知错误，登录已中止！");
                    }
                }
            }
            catch (Exception ex)
            {
                this.frmMain.WriteInfo("发送错误，登录已中止!错误详细信息：" + ex.Message);
                Log.WriteLog4Ex("Login", ex);
            }
            result = false;
            return result;
        }
        /// <summary>
        /// 得到验证码
        /// </summary>
        private void RefreshCheckCode()
        {
            try
            {
                Random random = new Random();
                this.picCheckCode.Image = this.frmMain.http.Getimg("https://dynamic.12306.cn/otsweb/passCodeAction.do?rand=lrand&" + random.NextDouble(), "image/png,image/*;q=0.8,*/*;q=0.5");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                Log.WriteLog4Ex("RefreshCheckCode", ex);
            }
        }
    }
}
